package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.RuleUtils;
import com.ruoyi.his.domain.*;
import com.ruoyi.his.domain.vo.HisDisposalStatistcs;
import com.ruoyi.his.domain.vo.HisWarningStatistcs;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.ruoyi.common.constant.HisConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.his.domain.vo.HisWarningStatistcsPre;
import com.ruoyi.his.domain.vo.VisitVo;
import com.ruoyi.his.mapper.OdsDoctorAllMapper;
import com.ruoyi.his.mapper.OdsDoctorDataMapper;
import com.ruoyi.his.mapper.OdsHospitalAllMapper;
import com.ruoyi.his.mapper.OdsHospitalDataMapper;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.HisHospitalNationVo;
import com.ruoyi.system.mapper.HisEngineAnalysisMapper;
import com.ruoyi.system.mapper.HisEngineRuleMapper;
import com.ruoyi.system.mapper.HisHospitalNationMapper;
import com.ruoyi.system.service.IHisEngineAnalysisService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class IHisEngineAnalysisServiceImpl implements IHisEngineAnalysisService {

    @Resource
    private HisEngineAnalysisMapper hisEngineAnalysisMapper;

    @Resource
    private HisHospitalNationMapper hisHospitalNationMapper;

    @Resource
    private OdsHospitalDataMapper odsHospitalDataMapper;

    @Resource
    private HisEngineRuleMapper hisEngineRuleMapper;
    @Resource
    private OdsHospitalAllMapper odsHospitalAllMapper;

    @Resource
    private OdsDoctorAllMapper odsDoctorAllMapper;

    @Value("${http.url}")
    private String url;

    @Override
    public List<HisVerifyOverdueWarning> verifyOverdueWarningList(HisVerifyOverdueWarning hisVerifyOverdueWarning) {
        return hisEngineAnalysisMapper.verifyOverdueWarningList(hisVerifyOverdueWarning);
    }

    @Override
    public List<HisLicensedOverWarning> hisLicensedOverWarningList(HisLicensedOverWarning hisLicensedOverWarning) {
        return hisEngineAnalysisMapper.hisLicensedOverWarningList(hisLicensedOverWarning);
    }

    @Override
    public List<HisChildBeyondWarning> hisChildBeyondWarning(HisChildBeyondWarning hisChildBeyondWarning) {
        List<HisChildBeyondWarning> hisChildBeyondWarnings = hisEngineAnalysisMapper.hisChildBeyondWarningList(hisChildBeyondWarning);
        List<OdsHospitalAll> hisHospitalNationVos = odsHospitalAllMapper.selectHisHospitalNew(new OdsHospitalAll());

        Map<String, OdsHospitalAll> map =
                hisHospitalNationVos.stream().filter(p->p.getHospitalId()!=null).collect(Collectors.toMap(
                        OdsHospitalAll::getHospitalId,
                        Function.identity(),
                        (key1 , key2) -> key1
                ));

        List<String> clinicIds = hisChildBeyondWarnings.stream().filter(v->StringUtils.isNotBlank(v.getClinicId())).map(HisChildBeyondWarning::getClinicId)
                .distinct().collect(Collectors.toList());

        String join = Joiner.on(",").join(clinicIds);

        if(StringUtils.isNotBlank(join)){
            String strs = HttpUtils.sendGet(url+"/clinic/get", "clinicIds=" + join);
            AjaxResult re = JSONObject.parseObject(strs, AjaxResult.class);
            JSONObject array = (JSONObject) re.get("data");
//        VisitVo visitVo = array.getObject(vo.getClinic_id(),VisitVo.class);
            if(array!=null){
                Iterator<HisChildBeyondWarning> iterator = hisChildBeyondWarnings.iterator();
                OdsDoctorAll param = new OdsDoctorAll();
                while (iterator.hasNext()){
                    HisChildBeyondWarning next = iterator.next();
                    String projectName = next.getProjectName();
                    JSONObject jsonObject = array.getJSONObject(next.getClinicId());
                    if(jsonObject!=null){
                        Integer patientAge = jsonObject.getInteger("patientAge");
                        String departmentName = jsonObject.getString("departmentName");
                        String registerNumber = jsonObject.getString("registerNumber");
                        String hospitalId = jsonObject.getString("hospitalId");
                        if (map.containsKey(hospitalId)){
                            OdsHospitalAll hisHospitalNationVo = map.get(hospitalId);
                            next.setHospitalName(hisHospitalNationVo.getInstitutionName());
                            next.setMedicalAreaname(hisHospitalNationVo.getMedicalAreaname());
                            if(!StringUtils.isEmpty(next.getDoctorCode())){
                                param.setDoctorCode(next.getDoctorCode());
                                List<OdsDoctorAll> list =odsDoctorAllMapper.selectOdsDoctorAllList(param);
                                if(list!=null&& list.size()>0){
                                    next.setDoctorName(list.get(0).getName());
                                }
                            }
                        }
                        next.setKeywords(patientAge +"岁/" + departmentName);
                    }
                }
            }
        }
        return hisChildBeyondWarnings;
    }

    @Override
    public List<HisChildBeyondWarning> hisChildBeyondWarningList(HisChildBeyondWarning hisChildBeyondWarning) {
        return hisEngineAnalysisMapper.hisChildBeyondWarningDetail(hisChildBeyondWarning);
    }

    @Override
    public List<HisChildBeyondWarning> hisChildBeyondWarningList1(HisChildBeyondWarning hisChildBeyondWarning) {
        return hisEngineAnalysisMapper.hisChildBeyondWarningDetail1(hisChildBeyondWarning);
    }
    @Override
    public List<HisPunish> childBeyondWarnInfo(HisPunish hisPunish) {
        return hisEngineAnalysisMapper.childBeyondWarnInfoDetail(hisPunish);
    }

    @Override
    public List<HisChildBeyondWarning> hisNoRightsKj(HisChildBeyondWarning hisChildBeyondWarning) {

        List<HisChildBeyondWarning> hisChildBeyondWarnings = hisEngineAnalysisMapper.hisNoRightsCfWarning(hisChildBeyondWarning);
        //取到抗菌处方权的
        List<String> medicinesByType = hisEngineAnalysisMapper.getMedicinesByType(HisConstants.KJ_MECIDINE);

        List<String> clinicIds = hisChildBeyondWarnings.stream().map(HisChildBeyondWarning::getClinicId)
                .distinct().collect(Collectors.toList());

        String join = Joiner.on(",").join(clinicIds);

        String strs = HttpUtils.sendGet(url+"/clinic/get", "clinicIds=" + join);
        AjaxResult re = JSONObject.parseObject(strs, AjaxResult.class);
        JSONObject array = (JSONObject) re.get("data");
        List<HisHospitalNationVo> hisHospitalNationVos = hisHospitalNationMapper.selectHisHospitalNationLists(new HisHospitalNation());
        Map<String, HisHospitalNationVo> map =
                hisHospitalNationVos.stream().collect(Collectors.toMap(
                        HisHospitalNationVo::getNumber,
                        Function.identity(),
                        (key1 , key2) -> key1
                ));
        Iterator<HisChildBeyondWarning> iterator = hisChildBeyondWarnings.iterator();
        while (iterator.hasNext()){
            HisChildBeyondWarning next = iterator.next();
            String projectName = next.getProjectName();
            Optional<String> first = medicinesByType.stream().filter(f -> {
                return projectName.contains(f);
            }).findFirst();
            if (first.isPresent()){
                next.setKeywords(first.get());
            }

            JSONObject jsonObject = array.getJSONObject(next.getClinicId());
            HisHospitalNationVo hospitalNationVo = map.get(jsonObject.getString("registerNumber"));
            if (Objects.nonNull(hospitalNationVo)){
                next.setHospitalName(hospitalNationVo.getName());
                next.setMedicalAreaname(hospitalNationVo.getAreaname());
            }
        }
        return hisChildBeyondWarnings;
    }

    @Override
    public HisWarningStatistcsPre getWarningStatistics(HisLicensedOverWarning hisVerifyOverdueWarning) {
        final List<HisWarningStatistcs> warningStatistics = hisEngineAnalysisMapper.getWarningStatistics(hisVerifyOverdueWarning);
        HisWarningStatistcsPre pre =new HisWarningStatistcsPre();
        pre.setTotal(warningStatistics.size());
        List<HisWarningStatistcs> statistcsList =new ArrayList<>();
        for (HisWarningStatistcs hisWarningStatistcs:warningStatistics){
            if(Objects.nonNull(hisWarningStatistcs)){
                if(StringUtils.isNotBlank(hisWarningStatistcs.getHospitalId())&&StringUtils.isNotBlank(hisWarningStatistcs.getSignature())){
                    final List<HisWarningStatistcs> warningStatisticPre = hisEngineAnalysisMapper.getWarningStatisticsPreLog(hisWarningStatistcs.getHospitalId(),hisVerifyOverdueWarning.getName(),hisWarningStatistcs.getSignature());
                    if(Objects.nonNull(warningStatisticPre)){
                        for (HisWarningStatistcs s:warningStatisticPre) {
                            s.setHospitalId(hisWarningStatistcs.getHospitalId());
                            s.setSignature(hisWarningStatistcs.getSignature());
                        }
                    }
                    statistcsList.addAll(warningStatisticPre);
                    for (HisWarningStatistcs s: statistcsList) {
                        s.setSum(warningStatisticPre.size());
                    }
                }
            }

        }
        pre.setList(statistcsList);
        return pre;
    }

    @Override
    public HisWarningStatistcsPre getWarningStatisticsHospital(HisVerifyOverdueWarning hisVerifyOverdueWarning) {
        final List<HisWarningStatistcs> warningStatistics = hisEngineAnalysisMapper.getWarningStatisticsHospital(hisVerifyOverdueWarning);
        HisWarningStatistcsPre pre =new HisWarningStatistcsPre();
        pre.setTotal(warningStatistics.size());
        List<HisWarningStatistcs> statistcsList =new ArrayList<>();
        for (HisWarningStatistcs hisWarningStatistcs:warningStatistics){
            if(Objects.nonNull(hisWarningStatistcs)){
                if(StringUtils.isNotBlank(hisWarningStatistcs.getHospitalId())&&StringUtils.isNotBlank(hisWarningStatistcs.getSignature())){
                    final List<HisWarningStatistcs> warningStatisticPre = hisEngineAnalysisMapper.getWarningStatisticsHospitalLog(hisWarningStatistcs.getHospitalId(),hisVerifyOverdueWarning.getHospitalName(),hisWarningStatistcs.getSignature());
                    statistcsList.addAll(warningStatisticPre);
                }
            }
        }
        pre.setList(statistcsList);
        return pre;
    }

    @Override
    public List<HisDisposalStatistcs> getDisposalStatistics(HisLicensedOverWarning hisLicensedOverWarning) {
        List<HisDisposalStatistcs> disposalStatistics = hisEngineAnalysisMapper.getDisposalStatistics(hisLicensedOverWarning);
        for (HisDisposalStatistcs statistcs:disposalStatistics){
            OdsHospitalData odsHospitalData = odsHospitalDataMapper.selectOne(new LambdaQueryWrapper<OdsHospitalData>()
                    .eq(OdsHospitalData::getHospitalId, statistcs.getHospitalId()));
            if(Objects.nonNull(odsHospitalData)){
                statistcs.setHospitalName(odsHospitalData.getName());

            }
        }
        return disposalStatistics;
    }

    @Override
    public HisChildBeyondWarningDetails hisChildBeyondWarningDetails(HisChildBeyondWarning hisChildBeyondWarning) {

        List<HisChildBeyondWarning> hisChildBeyondWarnings = hisEngineAnalysisMapper.hisChildBeyondWarningDetail1(hisChildBeyondWarning);

        HisChildBeyondWarningDetails hisChildBeyondWarningDetails = new HisChildBeyondWarningDetails();
        if (!CollectionUtils.isEmpty(hisChildBeyondWarnings)) {
            HisChildBeyondWarning hisChildBeyond = hisChildBeyondWarnings.get(0);
            String clinicId = hisChildBeyond.getClinicId();
            hisChildBeyondWarningDetails.setClinicId(clinicId);

            String strs = HttpUtils.sendGet(url + "/clinic/get", "clinicIds=" + clinicId);
            AjaxResult re = JSONObject.parseObject(strs, AjaxResult.class);
            if (re.get("data") != null) {
                JSONObject array = (JSONObject) re.get("data");
                if (array != null) {
                    JSONObject jsonObject = array.getJSONObject(clinicId);
                    hisChildBeyondWarningDetails.setClinicTime(jsonObject.getString("clinicTime"));
                    String registerNumber = jsonObject.getString("registerNumber");
                    String hospitalId = jsonObject.getString("hospitalId");

                    String signature = jsonObject.getString("signature");
                    hisChildBeyondWarningDetails.setSignature(signature);

                    OdsHospitalAll hisHospitalNation = new OdsHospitalAll();
                    hisHospitalNation.setHospitalId(hospitalId);
                    List<OdsHospitalAll> hisHospitalNationVos = odsHospitalAllMapper.selectHisHospitalNew(hisHospitalNation);
                    String hosName = "";
                    if (!CollectionUtils.isEmpty(hisHospitalNationVos)) {
                        OdsHospitalAll hisHospitalNationVo = hisHospitalNationVos.get(0);
                        hosName = hisHospitalNationVo.getInstitutionName();
                        hisChildBeyondWarningDetails.setHosname(hosName);
                        String num = hisHospitalNationVo.getRegisterNumber();
                        hisChildBeyondWarningDetails.setRegisterNumber(num);
                        hisChildBeyondWarningDetails.setHospitalId(hospitalId);
                    }

                    hisChildBeyondWarningDetails.setDeptname(jsonObject.getString("departmentName"));
                    Integer firstVisit = jsonObject.getInteger("firstVisit");
                    String visit = "";
                    if (firstVisit == 0) {
                        visit = "初诊";
                    } else if (firstVisit == 1) {
                        visit = "复诊";
                    }
                    hisChildBeyondWarningDetails.setFirstVisit(visit);

                    String medicalTypeString = "";
                    Integer medicalType = jsonObject.getInteger("medicalType");
                    if (medicalType == 0) {
                        medicalTypeString = "普通门诊";
                    } else if (medicalType == 1) {
                        medicalTypeString = "专家门诊";
                    } else if (medicalType == 2) {
                        medicalTypeString = "急诊";
                    }
                    hisChildBeyondWarningDetails.setMedicalType(medicalTypeString);
                    String doctorName = "";
                    String doctorCode = jsonObject.getString("doctorCode");
                    if (!StringUtils.isEmpty(doctorCode)) {
                        OdsDoctorAll param = new OdsDoctorAll();
                        param.setDoctorCode(doctorCode);
                        List<OdsDoctorAll> list = odsDoctorAllMapper.selectOdsDoctorAllList(param);
                        if (list != null && list.size() > 0) {
                            doctorName = list.get(0).getName();
                            hisChildBeyondWarningDetails.setDoctorName(doctorName);
                        }
                    }
                    hisChildBeyondWarningDetails.setDoctorCode(doctorCode);
                    String patientName = jsonObject.getString("patientName");
                    hisChildBeyondWarningDetails.setPatientName(patientName);
                    hisChildBeyondWarningDetails.setPatientAge(jsonObject.getInteger("patientAge"));
                    Integer patientSex = jsonObject.getInteger("patientSex");
                    String patientSexString = "";
                    if (patientSex == 1) {
                        patientSexString = "男";
                    } else if (patientSex == 2) {
                        patientSexString = "女";
                    } else if (patientSex == 9) {
                        patientSexString = "未声明";
                    } else if (patientSex == 0) {
                        patientSexString = "未知";
                    }
                    hisChildBeyondWarningDetails.setPatientSex(patientSexString);
                    hisChildBeyondWarningDetails.setChiefComplaint(jsonObject.getString("chiefComplaint"));
                    hisChildBeyondWarningDetails.setDiagnosisName(jsonObject.getString("diagnosisName"));

                    List<HisEngineWarnmedic> engineWarnMedic = hisEngineAnalysisMapper.getEngineWarnMedic(clinicId);
                    if (!CollectionUtils.isEmpty(engineWarnMedic)) {
                        hisChildBeyondWarningDetails.setMedicList(engineWarnMedic);
                    } else {
                        hisChildBeyondWarningDetails.setMedicList(new ArrayList<>());
                    }

                    Integer ruleGroupId = hisChildBeyond.getRuleGroupId();
                    HisEngineRule hisEngineRule = new HisEngineRule();
                    hisEngineRule.setRuleGroupId((long) ruleGroupId);
                    List<HisEngineRule> hisEngineRules = hisEngineRuleMapper.selectHisEngineRuleValueList(hisEngineRule);

                    List<HisEngineWarnRule> engineWarnRules = new ArrayList<>();
                    for (HisEngineRule engineRule : hisEngineRules) {
                        Long id = engineRule.getId();
                        Long ruleType = engineRule.getRuleType();
                        Integer ruleTypeInt = Integer.valueOf(ruleType.toString());
                        String ruleTypeName = RuleUtils.getRuleTypeName(ruleTypeInt);
                        String ruleContent = RuleUtils.getRuleContent(ruleTypeInt, doctorName, patientName, hosName, engineRule.getValue(), hisChildBeyond.getProjectName());
                        engineWarnRules.add(new HisEngineWarnRule(id.toString(), ruleTypeName, ruleContent));
                    }
                    hisChildBeyondWarningDetails.setWarnList(engineWarnRules);
                }
                hisChildBeyondWarningDetails.setPreId(hisChildBeyond.getPreId());
                hisChildBeyondWarningDetails.setPreTime(hisChildBeyond.getPreTime());
            }
        }
        return hisChildBeyondWarningDetails;
    }

    @Override
    public HisHasNoKjWarningDetails hisNoRightsKjDetails(HisChildBeyondWarning hisChildBeyondWarning) {
        List<HisChildBeyondWarning> hisChildBeyondWarnings = hisEngineAnalysisMapper.hisNoRightsCfWarning(hisChildBeyondWarning);

        HisHasNoKjWarningDetails hisHasNoKjWarningDetails = new HisHasNoKjWarningDetails();
        if (!CollectionUtils.isEmpty(hisChildBeyondWarnings)){
            HisChildBeyondWarning hisChildBeyond = hisChildBeyondWarnings.get(0);
            String clinicId = hisChildBeyond.getClinicId();
            hisHasNoKjWarningDetails.setClinicId(clinicId);
            hisHasNoKjWarningDetails.setRegisterNumber(hisChildBeyond.getRegisterNumber());
            String strs = HttpUtils.sendGet(url+"/clinic/get", "clinicIds=" + clinicId);
            AjaxResult re = JSONObject.parseObject(strs, AjaxResult.class);
            JSONObject array = (JSONObject) re.get("data");
            if (!array.isEmpty()){
                JSONObject jsonObject = array.getJSONObject(clinicId);
                hisHasNoKjWarningDetails.setClinicTime(jsonObject.getString("clinicTime"));
                String registerNumber = jsonObject.getString("registerNumber");

                HisHospitalNation hisHospitalNation = new HisHospitalNation();
                hisHospitalNation.setRegisterNumber(registerNumber);
                List<HisHospitalNationVo> hisHospitalNationVos = hisHospitalNationMapper.selectHisHospitalNationLists(hisHospitalNation);
                String hosName = "";
                if (!CollectionUtils.isEmpty(hisHospitalNationVos)){
                    HisHospitalNationVo hisHospitalNationVo = hisHospitalNationVos.get(0);
                    hosName = hisHospitalNationVo.getName();
                    hisHasNoKjWarningDetails.setHosname(hosName);
                }

                hisHasNoKjWarningDetails.setDeptname(jsonObject.getString("departmentName"));
                Integer firstVisit = jsonObject.getInteger("firstVisit");
                String visit = "";
                if (firstVisit == 0){
                    visit = "初诊";
                }else if (firstVisit == 1){
                    visit = "复诊";
                }
                hisHasNoKjWarningDetails.setFirstVisit(visit);

                String medicalTypeString = "";
                Integer medicalType = jsonObject.getInteger("medicalType");
                if (medicalType == 0){
                    medicalTypeString = "普通门诊";
                }else if (medicalType == 1){
                    medicalTypeString = "专家门诊";
                }else if (medicalType == 2){
                    medicalTypeString = "急诊";
                }
                hisHasNoKjWarningDetails.setMedicalType(medicalTypeString);
                String doctorName = jsonObject.getString("doctorName");
                hisHasNoKjWarningDetails.setDoctorName(doctorName);
                hisHasNoKjWarningDetails.setDoctorCode(jsonObject.getString("doctorCode"));
                String patientName = jsonObject.getString("patientName");
                hisHasNoKjWarningDetails.setPatientName(patientName);
                hisHasNoKjWarningDetails.setPatientAge(jsonObject.getInteger("patientAge"));
                Integer patientSex = jsonObject.getInteger("patientSex");
                String patientSexString = "";
                if (patientSex == 1){
                    patientSexString = "男";
                }else if (patientSex == 2){
                    patientSexString = "女";
                }else if (patientSex == 9){
                    patientSexString = "未声明";
                }else if (patientSex == 0){
                    patientSexString = "未知";
                }
                hisHasNoKjWarningDetails.setPatientSex(patientSexString);
                hisHasNoKjWarningDetails.setChiefComplaint(jsonObject.getString("chiefComplaint"));
                hisHasNoKjWarningDetails.setDiagnosisName(jsonObject.getString("diagnosisName"));

                List<HisEngineWarnmedic> engineWarnMedic = hisEngineAnalysisMapper.getEngineWarnMedic(clinicId);
                if (!CollectionUtils.isEmpty(engineWarnMedic)){
                    hisHasNoKjWarningDetails.setMedicList(engineWarnMedic);
                }

                Integer ruleGroupId = hisChildBeyond.getRuleGroupId();
                HisEngineRule hisEngineRule = new HisEngineRule();
                hisEngineRule.setRuleGroupId((long) ruleGroupId);
                List<HisEngineRule> hisEngineRules = hisEngineRuleMapper.selectHisEngineRuleValueList(hisEngineRule);

                List<HisEngineWarnRule> engineWarnRules = new ArrayList<>();
                for (HisEngineRule engineRule : hisEngineRules) {
                    Long id = engineRule.getId();
                    Long ruleType = engineRule.getRuleType();
                    Integer ruleTypeInt = Integer.valueOf(ruleType.toString());
                    String ruleTypeName = RuleUtils.getRuleTypeName(ruleTypeInt);
                    String ruleContent = RuleUtils.getRuleContent(ruleTypeInt, doctorName, patientName, hosName, engineRule.getValue(),hisChildBeyond.getProjectName());
                    engineWarnRules.add(new HisEngineWarnRule(id.toString(),ruleTypeName,ruleContent));
                }
                hisHasNoKjWarningDetails.setWarnList(engineWarnRules);
            }
            hisHasNoKjWarningDetails.setPreId(hisChildBeyond.getPreId());
            hisHasNoKjWarningDetails.setPreTime(hisChildBeyond.getPreTime());

        }

        return hisHasNoKjWarningDetails;
    }
}
